import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    products: [] // 购物车中的商品列表
  },
  getters: {
    cartProducts: state => state.products,
    cartTotal: state => state.products.reduce((total, product) => total + product.price * product.quantity, 0)
  },
  mutations: {
    ADD_PRODUCT(state, product) {
      let found = state.products.find(p => p.id === product.id);
      if (found) {
        found.quantity++;
      } else {
        state.products.push({ ...product, quantity: 1 });
      }
    },
    REMOVE_PRODUCT(state, productId) {
      state.products = state.products.filter(product => product.id !== productId);
    }
  },
  actions: {
    addProductToCart({ commit }, product) {
      commit('ADD_PRODUCT', product);
    },
    removeProductFromCart({ commit }, productId) {
      commit('REMOVE_PRODUCT', productId);
    }
  }
});